package com.scenic.rd_android.testview.animation;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.util.AttributeSet;

import static android.animation.ValueAnimator.INFINITE;

/**
 * Created by scenic on 2018/1/15.
 *
 * @see SearchViewActivity
 */

public class SearchView extends android.support.v7.widget.AppCompatImageView {


    public static int STATE_START = 1;
    public static int STATE_END = 2;
    private int state = -1;
    private float currentX;

    public SearchView(Context context) {
        super(context);

    }

    public SearchView(Context context, AttributeSet attrs) {
        super(context, attrs);

    }

    public SearchView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

    }



    public void stop() {
        if (animate != null) {
            animate.addListener(new Animator.AnimatorListener() {

                @Override
                public void onAnimationStart(Animator animation) {

                }

                @Override
                public void onAnimationEnd(Animator animation) {

                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {
                    int now = (int) getX();
                    int curr = (int) currentX;
                    if (now == curr) {
                        animate.cancel();
                        animate = null;
                    }

                }
            });

        }
        state = STATE_END;
    }

    ObjectAnimator animate;

    public void start() {

        if (state == STATE_START) {
            return;
        }
        currentX = getX();
        animate = ObjectAnimator.ofFloat(this, "X", currentX, currentX + 100f);

        animate.setRepeatCount(INFINITE);
        animate.setRepeatMode(ValueAnimator.REVERSE);

        animate.setDuration(2000).start();


        state = STATE_START;
    }
}
